package com.dsp.soundscape.client;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;

public class DomUtil {

	public static Element findChild (Element parent, String tagname) {
		return findChild(parent, tagname, null);
	}
	
	public static Element findChild (Element parent, String tagname, String classname) {
		for (int i = 0; i < DOM.getChildCount(parent); i++) {
			Element child = DOM.getChild(parent, i);
			if (child.getTagName().equalsIgnoreCase(tagname)) {
				if (classname == null || (child.getClassName() + " ").contains(classname + " ")) {
					return child;
				}
			}
			
			Element recursed = findChild(child, tagname, classname);
			if (recursed != null) {
				return recursed;
			}
		}
		
		return null;
	}
	
	public static List <Element> findChildren (Element parent, String tagname) {
		return findChildren(parent, tagname, null);
	}
	
	public static List <Element> findChildren (Element parent, String tagname, String classname) {
		List <Element> children = new ArrayList <Element>();
		for (int i = 0; i < DOM.getChildCount(parent); i++) {
			Element child = DOM.getChild(parent, i);
			if (child.getTagName().equalsIgnoreCase(tagname)) {
				if (classname == null || (child.getClassName() + " ").contains(classname + " ")) {
					children.add(child);
				}
			}
			
			children.addAll(findChildren(child, tagname, classname));
		}
		
		return children;
	}
}
